export default {
    name: "menus",
    setup(props, { emit }) {
        const tableRef = ref(null); // 表格引用
        const menus = ref(window.menus || []);
        const icons = ref([]);
        const allIcons = Object.keys(ElementPlusIconsVue);
        let loadedCount = 0;
        
        // 转换为虚拟滚动需要的格式
        const virtualOptions = computed(() => {
            return allIcons.map(icon => ({
                value: icon,
                label: icon
            }))
        })

		// 校验规则
		const validateRules = {
			name: {
				required: true,
				pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]{2,20}$/,
				message: '名称需2-20位，支持中文、英文、数字和下划线'
			},
			icon: {
				required: true,
			}
		}
		
		const validateIcon = (value) => {
            return !!value && allIcons.includes(value)
        }

		// 统一校验方法
		const validateMenus = () => {
			const errors = []
			menus.value.forEach((menu, index) => {
				// 校验菜单名称
				if (!menu.name?.trim()) {
					errors.push(`第 ${index + 1} 行：菜单名称不能为空`)
				} else if (!validateRules.name.pattern.test(menu.name)) {
					errors.push(`第 ${index + 1} 行：${validateRules.name.message}`)
				}
				// 校验图标
				if (validateRules.icon.required && !menu.icon) {
					errors.push(`第 ${index + 1} 行：请选择图标`)
				} else if (menu.icon && !validateIcon(menu.icon)) {
                    errors.push(`第 ${index + 1} 行：非法图标值`)
                }
			})
			return errors;
		}

		const saveMenus = async () => {
			const errors = validateMenus()
			if (errors.length > 0) {
				ElMessage.error({
					message: '校验失败：\n' + errors.join('\n'),
					duration: 5000,
					grouping: true
				})
				return
			}
		    if(window.APP_CONFIG.baseurl == 'https://zp1.kzhgzs.cn/') {
                return ElMessage.error('演示站禁止修改');
            }
			await savemenus(menus.value);
			ElMessage.success('保存成功');
			window.location.reload();
		}
		
        // 初始化拖拽排序
        onMounted(() => {
            nextTick(() => {
                const tableEl = tableRef.value?.$el;
                if (!tableEl) return;
                const tbody = tableEl.querySelector('.el-table__body-wrapper tbody');
                if (!tbody) return;

                new Sortable(tbody, {
                    animation: 150,
                    handle: '.drag-handle', // 指定拖拽手柄
                    onEnd: ({ oldIndex, newIndex }) => {
                        if (oldIndex === newIndex) return;
                        const newMenus = [...menus.value]; // 创建新数组
                        const [moved] = newMenus.splice(oldIndex, 1);
                        newMenus.splice(newIndex, 0, moved);
                        menus.value = newMenus; // 替换整个数组（触发响应式）
                    }
                });
            });
        });
        
        onUnmounted(() => {
            icons.value = [];
            menus.value = [];//释放内存
        })
			
        return {
            tableRef,
            validateIcon,
            virtualOptions,
            icons,
            menus,
            saveMenus,
            roles: {user: '普通', tby: '填报员', xmgly: '项目管理员', admin: '管理员'}
        };
    },
    
  template: `
	<div style="padding: 20px;background: #fff;border-radius: 8px;box-shadow: 0 2px 12px rgba(0,0,0,0.1);">
		<el-table :data="menus" ref="tableRef" row-key="name" style="width: 100%">
            <!-- 新增拖拽手柄列 -->
            <el-table-column label="排序" width="100">
                <template #default>
                    <el-icon class="drag-handle" style="cursor: move;">
                        <component :is="'Rank'" />
                    </el-icon>
                </template>
            </el-table-column>
            <el-table-column label="图标" width="230">
                <template #default="{ row }">
                    <el-select-v2 v-model="row.icon" :options="virtualOptions" :height="300" :item-size="40" placeholder="选择图标" clearable style="width: 100%" remote filterable>
                        <template #prefix>
                            <el-icon v-if="row.icon" style="margin-right: 8px" :size="20">
                                <component :is="row.icon" />
                            </el-icon>
                        </template>
                        
                        <template #default="{ item: icon }">
                            <div style="display: flex; align-items: center; height: 40px">
                                <el-icon><component :is="icon.value" /></el-icon>
                                <span style="margin-left: 8px">{{ icon.label }}</span>
                            </div>
                        </template>
                    </el-select-v2>
                </template>
            </el-table-column>
			
			<el-table-column label="菜单名称" width="260">
				<template #default="{ row }">
					<el-input v-model="row.name" placeholder="请输入菜单名称" style="padding: 20px 0;"/>
				</template>
			</el-table-column>
			
			<el-table-column label="全局显示" width="130">
				<template #default="{ row }">
					<el-switch v-model="row.visible" />
				</template>
			</el-table-column>
			
			<el-table-column label="角色显示【未选择则不显示】">
				<template #default="{ row }">
					<el-select v-model="row.roles" multiple placeholder="请选择" style="width: 100%">
    					<el-option v-for="(item, key) in roles" :key="key" :label="item" :value="key" />
    				</el-select>
				</template>
			</el-table-column>
		</el-table>
        
        <div style="margin-top: 20px;text-align:center;">
		    <el-button type="primary" size="large" @click="saveMenus">保存菜单</el-button>
        </div>
	</div>
  `
};